<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title} + ' - FTP管理系统'">用户管理 - FTP管理系统</title>

    <!-- Bootstrap CSS -->
    <link th:href="@{/webjars/bootstrap/5.3.0/css/bootstrap.min.css}" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://witmore.oss-cn-hangzhou.aliyuncs.com/cdn/npm/font-awesome/6.7.2/all.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link th:href="@{/css/admin.css}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <div class="admin-layout">
            <!-- 左侧边栏 -->
            <div class="sidebar">
                <div class="sidebar-brand">
                    <h4><i class="fas fa-server me-2"></i>FTP管理系统</h4>
                </div>
                <ul class="sidebar-menu">
                    <li>
                        <a href="/admin">
                            <i class="fas fa-tachometer-alt"></i>仪表盘
                        </a>
                    </li>
                    <li>
                        <a href="/admin/users" class="active">
                            <i class="fas fa-users"></i>用户管理
                        </a>
                    </li>
                    <li>
                        <a href="/admin/logs">
                            <i class="fas fa-list-alt"></i>操作日志
                        </a>
                    </li>
                    <li>
                        <a href="/admin/connections">
                            <i class="fas fa-plug"></i>连接管理
                        </a>
                    </li>
                    <li>
                        <a href="/admin/monitor">
                            <i class="fas fa-chart-line"></i>系统监控
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 主内容区域 -->
            <div class="main-content">
                <!-- 顶部导航栏 -->
                <div class="top-navbar">
                    <h1 class="page-title">用户管理</h1>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="/admin">首页</a></li>
                            <li class="breadcrumb-item active">用户管理</li>
                        </ol>
                    </nav>
                </div>

                <!-- 内容区域 -->
                <div class="content-wrapper">
                    <!-- 页面标题和操作按钮 -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div></div>
                        <button class="btn btn-primary" @click="showCreateModal">
                            <i class="fas fa-plus me-2"></i>添加用户
                        </button>
                    </div>

            <!-- 搜索和筛选 -->
            <div class="card mb-4">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control" placeholder="搜索用户名..."
                                       v-model="searchForm.username" @keyup.enter="loadUsers">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" v-model="searchForm.enabled">
                                <option value="">全部状态</option>
                                <option value="true">已启用</option>
                                <option value="false">已禁用</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-outline-primary me-2" @click="loadUsers">
                                <i class="fas fa-search me-1"></i>搜索
                            </button>
                            <button class="btn btn-outline-secondary" @click="resetSearch">
                                <i class="fas fa-undo me-1"></i>重置
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 用户列表 -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>主目录</th>
                                    <th>状态</th>
                                    <th>最大连接数</th>
                                    <th>写权限</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="user in users" :key="user.id">
                                    <td>{{ user.id }}</td>
                                    <td>
                                        <i class="fas fa-user me-2"></i>{{ user.username }}
                                    </td>
                                    <td>
                                        <code>{{ user.homeDirectory }}</code>
                                    </td>
                                    <td>
                                        <span class="badge" :class="user.enabled ? 'bg-success' : 'bg-danger'">
                                            {{ user.enabled ? '已启用' : '已禁用' }}
                                        </span>
                                    </td>
                                    <td>{{ user.maxConnections }}</td>
                                    <td>
                                        <i class="fas" :class="user.writePermission ? 'fa-check text-success' : 'fa-times text-danger'"></i>
                                    </td>
                                    <td>{{ formatDate(user.createTime) }}</td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button class="btn btn-outline-primary" @click="editUser(user)" title="编辑">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn"
                                                    :class="user.enabled ? 'btn-outline-warning' : 'btn-outline-success'"
                                                    @click="toggleUserStatus(user)"
                                                    :title="user.enabled ? '禁用' : '启用'">
                                                <i class="fas" :class="user.enabled ? 'fa-pause' : 'fa-play'"></i>
                                            </button>
                                            <button class="btn btn-outline-info" @click="resetPassword(user)" title="重置密码">
                                                <i class="fas fa-key"></i>
                                            </button>
                                            <button class="btn btn-outline-danger" @click="deleteUser(user)" title="删除">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr v-if="users.length === 0">
                                    <td colspan="8" class="text-center text-muted py-4">
                                        <i class="fas fa-inbox fa-2x mb-2"></i><br>
                                        暂无用户数据
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页组件 -->
                    <div v-if="pagination.total > 0" class="mt-4">
                        <div class="d-flex justify-content-end align-items-center flex-wrap">
                            <!-- 统计信息 -->
                            <div class="text-muted small me-4 mb-2">
                                <i class="fas fa-info-circle me-1"></i>
                                共 {{ pagination.total }} 条记录
                            </div>
                            
                            <!-- 每页显示选择器 -->
                            <div class="me-3 mb-2">
                                <label class="form-label mb-0 me-2 text-muted small">每页显示:</label>
                                <select class="form-select form-select-sm d-inline-block" 
                                        style="width: auto;" 
                                        v-model="pagination.size" 
                                        @change="changePageSize">
                                    <option value="10">10 条</option>
                                    <option value="20">20 条</option>
                                    <option value="50">50 条</option>
                                    <option value="100">100 条</option>
                                </select>
                            </div>
                            
                            <!-- 分页导航 -->
                            <nav v-if="pagination.pages > 1" class="mb-2">
                                <ul class="pagination pagination-sm mb-0">
                                    <!-- 首页 -->
                                    <li class="page-item" :class="{ disabled: pagination.current <= 1 }">
                                        <button class="page-link" 
                                                @click="changePage(1)" 
                                                :disabled="pagination.current <= 1"
                                                title="首页">
                                            <i class="fas fa-angle-double-left"></i>
                                        </button>
                                    </li>
                                    
                                    <!-- 上一页 -->
                                    <li class="page-item" :class="{ disabled: pagination.current <= 1 }">
                                        <button class="page-link" 
                                                @click="changePage(pagination.current - 1)" 
                                                :disabled="pagination.current <= 1"
                                                title="上一页">
                                            <i class="fas fa-angle-left"></i>
                                        </button>
                                    </li>
                                    
                                    <!-- 页码 -->
                                    <li class="page-item"
                                        v-for="page in getPageNumbers()"
                                        :key="page"
                                        :class="{ 
                                            active: page === pagination.current, 
                                            disabled: page === '...' 
                                        }">
                                        <button class="page-link"
                                                @click="page !== '...' ? changePage(page) : null"
                                                :disabled="page === '...'"
                                                :class="{ 'fw-bold': page === pagination.current }">
                                            {{ page }}
                                        </button>
                                    </li>
                                    
                                    <!-- 下一页 -->
                                    <li class="page-item" :class="{ disabled: pagination.current >= pagination.pages }">
                                        <button class="page-link" 
                                                @click="changePage(pagination.current + 1)" 
                                                :disabled="pagination.current >= pagination.pages"
                                                title="下一页">
                                            <i class="fas fa-angle-right"></i>
                                        </button>
                                    </li>
                                    
                                    <!-- 末页 -->
                                    <li class="page-item" :class="{ disabled: pagination.current >= pagination.pages }">
                                        <button class="page-link" 
                                                @click="changePage(pagination.pages)" 
                                                :disabled="pagination.current >= pagination.pages"
                                                title="末页">
                                            <i class="fas fa-angle-double-right"></i>
                                        </button>
                                    </li>
                                </ul>
                            </nav>
                            
                            <!-- 当只有一页时显示的信息 -->
                            <div v-else class="text-muted small mb-2">
                                <i class="fas fa-check-circle me-1 text-success"></i>
                                所有数据已显示完毕
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 创建/编辑用户模态框 -->
        <div class="modal fade" id="userModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="fas fa-user me-2"></i>{{ userForm.id ? '编辑用户' : '添加用户' }}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="saveUser">
                            <div class="mb-3">
                                <label class="form-label">用户名 *</label>
                                <input type="text" class="form-control" v-model="userForm.username"
                                       :disabled="userForm.id" required>
                            </div>
                            <div class="mb-3" v-if="!userForm.id">
                                <label class="form-label">密码 *</label>
                                <input type="password" class="form-control" v-model="userForm.password" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">主目录 *</label>
                                <input type="text" class="form-control" v-model="userForm.homeDirectory" required>
                                <div class="form-text">例如: /users/username</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">最大连接数</label>
                                <input type="number" class="form-control" v-model="userForm.maxConnections" min="1" max="100">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">每IP最大连接数</label>
                                <input type="number" class="form-control" v-model="userForm.maxConnectionsPerIp" min="1" max="10">
                            </div>
                            <div class="mb-3 form-check">
                                <input type="checkbox" class="form-check-input" v-model="userForm.enabled" id="enabled">
                                <label class="form-check-label" for="enabled">启用用户</label>
                            </div>
                            <div class="mb-3 form-check">
                                <input type="checkbox" class="form-check-input" v-model="userForm.writePermission" id="writePermission">
                                <label class="form-check-label" for="writePermission">写权限</label>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" @click="saveUser">
                            <i class="fas fa-save me-2"></i>保存
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 重置密码模态框 -->
        <div class="modal fade" id="passwordModal" tabindex="-1">
            <div class="modal-dialog modal-sm">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="fas fa-key me-2"></i>重置密码
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" :value="passwordForm.username" disabled>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">新密码 *</label>
                            <input type="password" class="form-control" v-model="passwordForm.newPassword" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" @click="savePassword">
                            <i class="fas fa-save me-2"></i>保存
                        </button>
                    </div>
                </div>
            </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script th:src="@{/webjars/bootstrap/5.3.0/js/bootstrap.bundle.min.js}"></script>

    <script>
        const { createApp } = Vue;

        createApp({
            data() {
                return {
                    users: [],
                    searchForm: {
                        username: '',
                        enabled: ''
                    },
                    pagination: {
                        current: 1,
                        size: 10,
                        total: 0,
                        pages: 0
                    },
                    userForm: {
                        id: null,
                        username: '',
                        password: '',
                        homeDirectory: '',
                        maxConnections: 5,
                        maxConnectionsPerIp: 2,
                        enabled: true,
                        writePermission: true
                    },
                    passwordForm: {
                        id: null,
                        username: '',
                        newPassword: ''
                    }
                }
            },
            mounted() {
                this.loadUsers();
            },
            methods: {
                async loadUsers() {
                    try {
                        const params = {
                            page: this.pagination.current,
                            size: this.pagination.size,
                            ...this.searchForm
                        };

                        const response = await axios.get('/api/ftp/users', { params });
                        if (response.data.code === 200) {
                            this.users = response.data.records || [];

                            // 处理分页数据 - 兼容不同的响应格式
                            if (response.data.total !== undefined) {
                                this.pagination.total = response.data.total;
                            } else if (response.data.page && response.data.page.total !== undefined) {
                                this.pagination.total = response.data.page.total;
                            } else {
                                this.pagination.total = this.users.length;
                            }

                            if (response.data.pages !== undefined) {
                                this.pagination.pages = response.data.pages;
                            } else if (response.data.page && response.data.page.totalPage !== undefined) {
                                this.pagination.pages = response.data.page.totalPage;
                            } else {
                                this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.size);
                            }
                        }
                    } catch (error) {
                        console.error('加载用户列表失败:', error);
                        alert('加载用户列表失败');
                    }
                },
                showCreateModal() {
                    this.userForm = {
                        id: null,
                        username: '',
                        password: '',
                        homeDirectory: '',
                        maxConnections: 5,
                        maxConnectionsPerIp: 2,
                        enabled: true,
                        writePermission: true
                    };
                    new bootstrap.Modal(document.getElementById('userModal')).show();
                },
                editUser(user) {
                    this.userForm = { ...user };
                    new bootstrap.Modal(document.getElementById('userModal')).show();
                },
                async saveUser() {
                    try {
                        if (this.userForm.id) {
                            // 更新用户
                            await axios.put(`/api/ftp/users/${this.userForm.id}`, this.userForm);
                        } else {
                            // 创建用户
                            await axios.post('/api/ftp/users', this.userForm);
                        }

                        bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
                        this.loadUsers();
                        alert('保存成功');
                    } catch (error) {
                        console.error('保存用户失败:', error);
                        alert('保存用户失败: ' + (error.response?.data?.message || error.message));
                    }
                },
                async toggleUserStatus(user) {
                    try {
                        await axios.put(`/api/ftp/users/${user.id}/status?enabled=${!user.enabled}`);
                        this.loadUsers();
                        alert(`用户已${!user.enabled ? '启用' : '禁用'}`);
                    } catch (error) {
                        console.error('切换用户状态失败:', error);
                        alert('操作失败');
                    }
                },
                resetPassword(user) {
                    this.passwordForm = {
                        id: user.id,
                        username: user.username,
                        newPassword: ''
                    };
                    new bootstrap.Modal(document.getElementById('passwordModal')).show();
                },
                async savePassword() {
                    try {
                        await axios.put(`/api/ftp/users/${this.passwordForm.id}/password?newPassword=${this.passwordForm.newPassword}`);
                        bootstrap.Modal.getInstance(document.getElementById('passwordModal')).hide();
                        alert('密码重置成功');
                    } catch (error) {
                        console.error('重置密码失败:', error);
                        alert('重置密码失败');
                    }
                },
                async deleteUser(user) {
                    if (confirm(`确定要删除用户 "${user.username}" 吗？`)) {
                        try {
                            await axios.delete(`/api/ftp/users/${user.id}`);
                            this.loadUsers();
                            alert('删除成功');
                        } catch (error) {
                            console.error('删除用户失败:', error);
                            alert('删除失败');
                        }
                    }
                },
                resetSearch() {
                    this.searchForm = { username: '', enabled: '' };
                    this.pagination.current = 1;
                    this.loadUsers();
                },
                changePage(page) {
                    if (page >= 1 && page <= this.pagination.pages) {
                        this.pagination.current = page;
                        this.loadUsers();
                    }
                },
                changePageSize() {
                    this.pagination.current = 1;
                    this.loadUsers();
                },
                getPageNumbers() {
                    const pages = [];
                    const total = this.pagination.pages;
                    const current = this.pagination.current;

                    if (total <= 5) {
                        for (let i = 1; i <= total; i++) {
                            pages.push(i);
                        }
                    } else {
                        if (current <= 3) {
                            for (let i = 1; i <= 5; i++) {
                                pages.push(i);
                            }
                            if (total > 5) {
                                pages.push('...');
                                pages.push(total);
                            }
                        } else if (current >= total - 2) {
                            pages.push(1);
                            if (total > 5) {
                                pages.push('...');
                            }
                            for (let i = total - 4; i <= total; i++) {
                                pages.push(i);
                            }
                        } else {
                            pages.push(1);
                            pages.push('...');
                            for (let i = current - 1; i <= current + 1; i++) {
                                pages.push(i);
                            }
                            pages.push('...');
                            pages.push(total);
                        }
                    }

                    return pages;
                },
                formatDate(dateStr) {
                    if (!dateStr) return '';
                    return new Date(dateStr).toLocaleString('zh-CN');
                }
            }
        }).mount('#app');
    </script>

    <style>
        /* 分页样式优化 */
        .pagination .page-item.active .page-link {
            background-color: #007bff !important;
            border-color: #007bff !important;
            color: #ffffff !important;
            font-weight: bold;
        }
        
        .pagination .page-item.active .page-link:hover {
            background-color: #0056b3 !important;
            border-color: #0056b3 !important;
            color: #ffffff !important;
        }
        
        .pagination .page-link {
            color: #007bff;
            border: 1px solid #dee2e6;
            padding: 0.375rem 0.75rem;
            margin: 0 2px;
            border-radius: 0.375rem;
            transition: all 0.2s ease-in-out;
        }
        
        .pagination .page-link:hover {
            color: #0056b3;
            background-color: #e9ecef;
            border-color: #dee2e6;
        }
        
        .pagination .page-item.disabled .page-link {
            color: #6c757d;
            background-color: #fff;
            border-color: #dee2e6;
        }
        
        .pagination .page-item.disabled .page-link:hover {
            color: #6c757d;
            background-color: #fff;
            border-color: #dee2e6;
        }
        
        /* 分页大小选择器样式 */
        .form-select-sm {
            border-radius: 0.375rem;
            border: 1px solid #ced4da;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        
        .form-select-sm:focus {
            border-color: #86b7fe;
            outline: 0;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }
    </style>
</body>
</html>
